/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import org.aspectj.weaver.ast.Var;
import org.springblade.common.utils.ValidList;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.CustomPartsLogDTO;
import org.springblade.modules.admin.dto.parts.SparepartPricesSearchDTO;
import org.springblade.modules.admin.entity.CustomPartsLog;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.vo.PlanApproveVO;
import org.springblade.modules.admin.vo.SparepartPricesVO;
import org.springframework.web.bind.annotation.*;
import org.springblade.modules.admin.service.ICustomPartsLogService;
import org.springblade.core.boot.ctrl.BladeController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 自定义部件log 控制器
 *
 * @author ysq
 * @since 2024-01-02
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/custompartslog")
@Api(value = "自定义部件log", tags = "自定义部件log接口")
public class CustomPartsLogController extends BladeController {

	private final ICustomPartsLogService customPartsLogService;

	/**
	 * 新增自定义部件log
	 *
	 * @param customPartsLogDTO CustomPartsLogDTO
	 * @return R 是否成功
	 */
	@PostMapping("/add/log")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增日志", notes = "传入customPartsLog")
	public R<Boolean> addLog(@RequestBody CustomPartsLogDTO customPartsLogDTO) {
		return R.status(customPartsLogService.addLog(customPartsLogDTO));
	}

	/**
	 * 自定义部件excel 导出
	 */
	@GetMapping("/export")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "导出")
	public void export(HttpServletResponse response) throws IOException {
		//获取结果列表，获取 解析json 数据
		List<CustomPartsLog> sourceList = customPartsLogService.list();
		//导出操作
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList
				("任务ID", "上级任务", "关联任务ID", "任务种类", "具体位置", "租户",
					"用户名称", "联系电话", "自定义配件", "提交时间");
			rows.add(title);
			if (Func.isNotEmpty(sourceList)) {
				for (CustomPartsLog c : sourceList) {
					Map<String, Object> recordMap = jsonToMap(c.getRecords());
					Map<String, Object> messageMap = jsonToMap(c.getPlanMessage());
					List<String> row = new ArrayList<>(16);
					row.add(Convert.toStr(c.getPlanId()));
					String planLinks = "";
					if(!Func.isNull(messageMap.getOrDefault("planLinks", "-"))) {
						planLinks = (String) messageMap.getOrDefault("planLinks", "-");
						String planLinksString = splitTypeList(planLinks);
						row.add(Convert.toStr(planLinksString));
					}else{
						row.add("-");
					}
					row.add(Convert.toStr(messageMap.getOrDefault("planIds", "-")));
					Integer typeStatus = (Integer) messageMap.getOrDefault("typeStatus", "-1");
					// 根据typeStatus 获取对应的任务种类
					if (typeStatus == -1) {
						row.add("-");
					} else {
						String typeStatusString = MaintainPlanContentEnum.getName(typeStatus);
						row.add(Convert.toStr(typeStatusString));
					}
					// 具体位置
					row.add(Convert.toStr(messageMap.getOrDefault("fromLocation", "-")));
					// 租户
					row.add(Convert.toStr(messageMap.getOrDefault("tenantName", "-")));
					// 用户名称
					row.add(Convert.toStr(messageMap.getOrDefault("userName", "-")));
					// 联系电话
					row.add(Convert.toStr(messageMap.getOrDefault("userPhone", "-")));
					// 自定义配件
					row.add(Convert.toStr(recordMap.getOrDefault("customPartPath", "-")));
					// 提交时间
					row.add(Convert.toStr(c.getCreateTime()));
					rows.add(row);
				}
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}
	}

	/**
	 * 功能描述：json to map
	 */
	private Map<String, Object> jsonToMap(String jsonStr) {
		JSONObject recordJsonObject = JSON.parseObject(jsonStr);
		return new HashMap<>(recordJsonObject);
	}

	/**
	 * 功能描述：类型列表拆分并返回String
	 */
	private String splitTypeList(String typeList) {
		if (Func.isEmpty(typeList)) {
			return "-";
		}
		String[] typeArr = typeList.split(",");
		StringBuilder typeStr = new StringBuilder();
		for (String s : typeArr) {
			switch (s) {
				case "0":
					typeStr.append(MaintainPlanContentEnum.MAINTAIN_ZC.getName()).append(";");
					break;
				case "1":
					typeStr.append(MaintainPlanContentEnum.MAINTAIN_BY.getName()).append(";");
					break;
				case "2":
					typeStr.append(MaintainPlanContentEnum.MAINTAIN_WX.getName()).append(";");
					break;
				case "3":
					typeStr.append(MaintainPlanContentEnum.MAINTAIN_KR.getName()).append(";");
					break;
				case "4":
					typeStr.append(MaintainPlanContentEnum.MAINTAIN_PARTS.getName()).append(";");
					break;
				case "5":
					typeStr.append(MaintainPlanContentEnum.MAINTAIN_AFFAIR.getName()).append(";");
					break;
				case "6":
					typeStr.append(MaintainPlanContentEnum.MAINTAIN_CHECK.getName()).append(";");
					break;
				default:
					typeStr.append("-").append(";");
					break;
			}
		}
		return typeStr.toString();
	}


	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
